package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author : Jungle
 * @Description :
 */
@Configuration
public class GuliFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、RequestContextHolder 拿到刚进来的这个请求, 相当于  HttpServletRequest request
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //两个异步任务查询购物项 查询地址列表需要传递请求头的cookie  （需要登录状态）
                //查询库存不需要，所以这里可以判空  （这里不用登录，如果需要登录状态也需要把 setRequestAttributes(requestAttributes)）
                if (attributes!=null) {
                    HttpServletRequest request = attributes.getRequest();
                    if (request!=null) {
                        // 同步请求头数据 Cookie
                        String cookie = request.getHeader("Cookie");
                        //给新请求同步了老请求的cookie
                        template.header("Cookie", cookie);
                    }
                }
            }
        };


        //return template -> {
        //    //1、RequestContextHolder 拿到刚进来的这个请求, 相当于  HttpServletRequest request
        //            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //            HttpServletRequest request = attributes.getRequest();
        //        // 同步请求头数据 Cookie
        //            String cookie = request.getHeader("Cookie");
        //            //给新请求同步了老请求的cookie
        //            template.header("Cookie", cookie);
        //};

    }
}
